package com.fangdada.demowebfulx2.router;


import com.fangdada.demowebfulx2.handler.TimeHandler;
import com.fangdada.demowebfulx2.handler.UserHandler;
import com.fangdada.demowebfulx2.service.UserService;
import com.fangdada.demowebfulx2.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;

import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;

import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.netty.http.server.HttpServer;

/**
 * @Author: fd
 * @Date 2021/11/30 16:03
 * @Description:
 */
public class RouterServer {

	@Autowired
	private TimeHandler timeHandler;

	//1 创建 Router 路由
	public RouterFunction<ServerResponse> routingFunction() {
		//创建 hanler 对象
		UserService userService = new UserServiceImpl();
		UserHandler handler = new UserHandler(userService);
		//设置路由
		return RouterFunctions
				.route(GET("/time"),req -> timeHandler.getTime(req))
				.andRoute(GET("/date"), timeHandler::getDate);
//				.route(GET("/users/{id}").and(accept(APPLICATION_JSON)), handler::getUserById)
//				.route(GET("/users").and(accept(APPLICATION_JSON)), handler::getAllUser);
	}

	//2 创建服务器完成适配
	public void createReactorServer() {
		//路由和 handler 适配
		RouterFunction<ServerResponse> route = routingFunction();
		HttpHandler httpHandler = toHttpHandler(route);
		ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
		//创建服务器
		HttpServer httpServer = HttpServer.create();
		//立即生效
		httpServer.handle(adapter).bindNow();
	}

	//最终调用
	public static void main(String[] args) throws Exception{
		RouterServer server = new RouterServer();
		server.createReactorServer();
		System.out.println("enter to exit");
		System.in.read();
	}

}
